package com.gcj.demo.controller;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

public class PropertiesUtil {

    public static final String path = "/b.properties";
    public static final Properties p = new Properties();

    public static void main(String[] args) {

    }

    /**
     * 初始化
     */
    public  void init() {
        FileInputStream inputStream = null;
        try {

             inputStream = new FileInputStream(this.getClass().getResource("/").getPath()+path);
            p.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据key 获取键值
     * @param key
     * @return
     */
    public static String get(String key){

        return p.getProperty(key);
    }

    /**
     * 插入或修改键值
     * @param key
     * @param value
     */
    public static void put(String key,String value){
        p.setProperty(key,value);
        FileOutputStream outputStream=null;
        try {
             outputStream = new FileOutputStream(path);
             p.store(outputStream,"");
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过key删除value
     * @param key
     */
    public static void delete(String key) {
        p.remove(key);
        FileOutputStream oFile = null;
        try {
            oFile = new FileOutputStream(path);
            p.store(oFile, "");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 循环所有key value
     */
    public static void list() {
        Enumeration en = p.propertyNames(); //得到配置文件的名字
        while(en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = p.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }
    }
}
